package xyz.whiteblue.controller;

import org.apache.commons.lang3.StringEscapeUtils;
import xyz.whiteblue.core.UrlAction;
import xyz.whiteblue.kit.JsonKit;
import xyz.whiteblue.render.RenderFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by WhiteBlue on 15/6/10.
 */
public class Controller {
    RenderFactory renderFactory;
    private HttpServletRequest request;
    private HttpServletResponse response;
    private UrlAction urlAction;

    public void init(HttpServletRequest request, HttpServletResponse response, RenderFactory renderFactory, UrlAction urlAction) {
        this.request = request;
        this.response = response;
        this.renderFactory = renderFactory;
        this.urlAction = urlAction;
    }

    public String getPara(String key) {
        String back = StringEscapeUtils.escapeHtml4(request.getParameter(key));
        return back;
    }

    public String getUrlPara(int index) {
        return urlAction.getUrlPara(index);
    }

    public void setAttr(String key, Object value) {
        request.setAttribute(key, value);
    }

    public void renderJson(Object object) {
        JsonKit.renderJsonObject(response, object);
    }

    public void render(String view) {
        renderFactory.getBeetlRender(view).render();
    }

    public void redirect(String url) {
        renderFactory.getRedirectRender(url).render();
    }

    public void renderError(int errorNumber) {
        renderFactory.getErrorRender(errorNumber).render();
    }

    public HttpServletRequest getRequest() {
        return request;
    }

    public HttpServletResponse getResponse() {
        return response;
    }

}
